﻿using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;

namespace Super.Hmi.Behavior
{
    public static class KeyBindingBehavior
    {
        public static ObservableCollection<KeyBinding> GetKeyBindings(DependencyObject obj)
        {
            return (ObservableCollection<KeyBinding>)obj.GetValue(KeyBindingsProperty);
        }
        public static void SetKeyBindings(DependencyObject obj, ObservableCollection<KeyBinding> value)
        {
            obj.SetValue(KeyBindingsProperty, value);
        }
        public static readonly DependencyProperty KeyBindingsProperty = DependencyProperty.RegisterAttached("KeyBindings", typeof(ObservableCollection<KeyBinding>), typeof(KeyBindingBehavior), new PropertyMetadata(null, OnKeyBindingsChanged));
        private static void OnKeyBindingsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not UIElement element) return;
            element.InputBindings.Clear();
            if (e.NewValue is ObservableCollection<KeyBinding> keyBindings)
            {
                foreach (var keyBinding in keyBindings)
                {
                    element.InputBindings.Add(keyBinding);
                }
                keyBindings.CollectionChanged += (sender, args) =>
                {
                    if (args.NewItems != null)
                    {
                        foreach (KeyBinding item in args.NewItems)
                        {
                            element.InputBindings.Add(item);
                        }
                    }
                    if (args.OldItems != null)
                    {
                        foreach (KeyBinding item in args.OldItems)
                        {
                            element.InputBindings.Remove(item);
                        }
                    }
                };
            }
        }
    }
}
